package com.sgb.kjwl.view.ui.activity.self.authentication;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityInvoiceAuthBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.DictEntity;
import com.sgb.kjwl.model.entity.user.SupplierAuthEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.AuthEvent;
import com.sgb.kjwl.view.ui.SinglePickBuilder;
import com.sgb.kjwl.view.widget.AddressPopWindow;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.self.InvocieAuthModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

public class InvoiceAuthActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener, BasePopWindow.OnResultClick {
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private ActivityInvoiceAuthBinding binding;
    private List<String> typeList;
    private List<DictEntity> dictEntityList;
    //    private CompanyPopWindow companyPopWindow;
    private AddressPopWindow addressPopWindow;
    private DictEntity dict;
    private int typePosition;
    private int businessPosition;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    @Inject
    InvocieAuthModel viewModel;

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, InvoiceAuthActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(InvoiceAuthActivity.this, R.layout.activity_invoice_auth);
        binding.setViewModel(viewModel);
        binding.include.actionBarTitle.setText(getResources().getString(R.string.company_auth));
        binding.include.actionBarImageLeft.setVisibility(View.VISIBLE);
        binding.include.actionBarImageLeft.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvType.setOnWholeItemClickListener(this);
        binding.itemTvSetUpDate.setOnWholeItemClickListener(this);
        binding.itemSetLocate.setOnWholeItemClickListener(this);
//        binding.itemTvBusinessScope.setOnWholeItemClickListener(this);
//        binding.itemTvRegisteredAddress.setOnWholeItemClickListener(this);
    }

    private void showInfoView(SupplierAuthEntity supplierAuthEntity) {

        viewModel.supplierAuthEntity.set(supplierAuthEntity);
        //item_tv_name
        binding.itemTvName.setContent(supplierAuthEntity.getCompanyName());
        //
        binding.itemTvCreditCode.setContent(supplierAuthEntity.getCreditCode());
        //
        binding.itemTvType.setContent(supplierAuthEntity.getCompanyType());
        //
//        binding.etScope.setText(supplierAuthEntity.getBusiness());
        //
        binding.itemTvArtificialPerson.setContent(supplierAuthEntity.getLegalPerson());
        //
        binding.itemTvRegisteredCapital.setContent(supplierAuthEntity.getRegisteredCapital());
        //
        binding.itemTvSetUpDate.setContent(supplierAuthEntity.getEstablishmentDate());
        //
        binding.markEt.setText(supplierAuthEntity.getCompanyAddress());

    }

    @Override
    protected void init() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
       /* companyPopWindow = new CompanyPopWindow(getActivity());
        companyPopWindow.setBgView(binding.grayLayout);
        companyPopWindow.setOnResultClick(this);*/


        addressPopWindow = new AddressPopWindow(getActivity());
        addressPopWindow.setBgView(binding.grayLayout);
        addressPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {

            @Override
            public void result(Object key1, Object key2, Object key3) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.action_bar_image_left:
                finish();
                break;
            case R.id.next_view:
                if (TextUtils.isEmpty(binding.itemTvName.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "企业名称不能为空");
                    return;
                }
                if (TextUtils.isEmpty(binding.itemTvCreditCode.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "统一社会信用代码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(binding.itemTvType.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "企业类型不能为空");
                    return;
                }
                if (TextUtils.isEmpty(binding.itemTvArtificialPerson.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "法定代表人不能为空");
                    return;
                }
                if (TextUtils.isEmpty(binding.itemTvRegisteredCapital.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "注册资本不能为空");
                    return;
                }

                if (TextUtils.isEmpty(binding.itemTvSetUpDate.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "成立日期不能为空");
                    return;
                }

                if (TextUtils.isEmpty(binding.markEt.getText())) {
                    MToast.showToast(InvoiceAuthActivity.this, "详细注册地址不能为空");
                    return;
                }

                if (TextUtils.isEmpty(binding.itemSetLocate.getContent())) {
                    MToast.showToast(InvoiceAuthActivity.this, "注册地址不能为空");
                    return;
                }

                setCurrentData();
                viewModel.commitCompanyAuth();

//                EventBus.getDefault().postSticky(AuthEvent.make().setMessageTag(EventConstant.EVENT_SELF_TICKS_INFO).setMessageData(viewModel.supplierAuthEntity.get()));
//                OpenTicksInfoActivity.start(this);
                break;
        }
    }

    private void setCurrentData() {
        viewModel.supplierAuthEntity.get().setCompanyName(binding.itemTvName.getContent());
        viewModel.supplierAuthEntity.get().setCreditCode(binding.itemTvCreditCode.getContent());
        viewModel.supplierAuthEntity.get().setCompanyType(binding.itemTvType.getContent());
//        viewModel.supplierAuthEntity.get().setBusiness(binding.etScope.getText().toString());
        viewModel.supplierAuthEntity.get().setLegalPerson(binding.itemTvArtificialPerson.getContent());
        viewModel.supplierAuthEntity.get().setRegisteredCapital(binding.itemTvRegisteredCapital.getContent());
        viewModel.supplierAuthEntity.get().setEstablishmentDate(binding.itemTvSetUpDate.getContent());
        viewModel.supplierAuthEntity.get().setCompanyAddress(binding.markEt.getText().toString());
        viewModel.supplierAuthEntity.get().setProvinceNo(addressEntityList.get(cityPosition1).getNo());
        viewModel.supplierAuthEntity.get().setCityNo(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getNo());
        viewModel.supplierAuthEntity.get().setDistrictNo(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(cityPosition3).getNo());

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(AuthEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SELF_INVOICE_INFO) {
            SupplierAuthEntity supplierAuthEntity = (SupplierAuthEntity) event.getMessageData();
            showInfoView(supplierAuthEntity);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    //企业类型
    public void showTypePop(List<String> datas) {
        this.typeList = datas;
        showTypePop();
    }

    private void showTypePop() {
        //条件选择器
        OptionsPickerView typeOption = new SinglePickBuilder(InvoiceAuthActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = typeList.get(options1);
                binding.itemTvType.setContent(content);
                typePosition = options1;
            }
        }).build();
        typeOption.setPicker(typeList);
        typeOption.setSelectOptions(typePosition);
        typeOption.show();
    }

    //经营范围
//    public void showBusinessPop(List<DictEntity> datas) {
//        this.dictEntityList = datas;
//        showBusinessPop();
//    }

//    private void showBusinessPop() {
//        OptionsPickerView businessOption = new SinglePickBuilder(InvoiceAuthActivity.this, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                String content = dictEntityList.get(options1).getName();
//                binding.itemTvBusinessScope.setContent(content);
//                businessPosition = options1;
//            }
//
//        }).build();
//        businessOption.setPicker(dictEntityList);
//        businessOption.setSelectOptions(businessPosition);
//        businessOption.show();
//    }

    //注册地址
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
//        opt2.clear();
//        opt3.clear();
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(InvoiceAuthActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                }
                String content = addressEntityList.get(options1).getName()
                        + opt2.get(options1).get(options2).getName()
                        + areaName;
                binding.itemSetLocate.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //时间选择器
    public void showTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(InvoiceAuthActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                binding.itemTvSetUpDate.setContent(format);
            }
        }).setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).setRangDate(null, Calendar.getInstance()).build();
        timePicker.show();
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_type:
                if (typeList != null) {
                    showTypePop();
                } else {
                    viewModel.getCompanyTypeModel();
                }
                break;
            case R.id.item_tv_set_up_date:
                showTimePop();
                break;
//            case R.id.item_tv_business_scope:
//                if (dictEntityList != null) {
//                    showBusinessPop();
//                } else {
//                    viewModel.getBusinessModel();
//                }
//                break;
            case R.id.item_set_locate:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }

                break;
        }
    }


    @Override
    public void result(Object key1, Object key2, Object key3) {
        binding.itemTvType.setContent((String) key1);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> entity : addressEntityList) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(entity.getChildren());
            for (int i = 0; i < entity.getChildren().size(); i++) {
                cityList.add(entity.getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (entity.getChildren().get(i).getChildren() == null
                        || entity.getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(entity.getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }
}
